package com.suxin.logger.handler;

import com.suxin.logger.Level;
import com.suxin.logger.LogManager;
import com.suxin.logger.LogRecord;
import com.suxin.logger.formatter.XMLFormatter;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Tang
 * @classname FileHandler
 * @description [  ]
 * @date 2022/4/27 13:32
 */
public class FileHandler extends StreamHandler{

    private String pattern;
    private boolean append;

    private static final Set<String> locks = new HashSet<>();
    private FileChannel lockFileChannel;
    private String lockFileName;

    private void configure() {
        LogManager logManager = LogManager.getLogManager();
        String cname = getClass().getName();
        this.pattern = logManager.getProperty(cname + ".pattern", "%h/java%u.log");
        setLevel(Level.INFO);
        setFormatter(new XMLFormatter());
        setFilter(null);
    }

    public FileHandler() {
        configure();
        try {
            openFiles();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public FileHandler(String pattern, boolean append) {
        configure();
        try {
            openFiles();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        this.pattern = pattern;
        this.append = append;
    }

    private void openFiles() throws FileNotFoundException {
        int unique = -1;
        for (; ; ) {
            unique++;
            // 生成一个加锁的文件名
            lockFileName = generate(pattern, 0, unique).toString() + ".lck";
            if (locks.contains(lockFileName)) {
                continue;
            }
            Path path = Paths.get(lockFileName);
            FileChannel channel = null;
            try {
                channel = FileChannel.open(path, StandardOpenOption.CREATE_NEW,
                        StandardOpenOption.WRITE);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (channel == null) {
                return;
            }
            lockFileChannel = channel;
            boolean available = false;
            try {
                available = lockFileChannel.tryLock() != null;
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (available) {
                locks.add(lockFileName);
                break;
            }
            try {
                lockFileChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        File file = generate(pattern, 0, unique);
        if (append) {
            open(file, true);
        } else {
            open(file, false);
        }
    }


    @Override
    public void close() {
        super.close();
        if (lockFileChannel != null) {
            try {
                lockFileChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 解锁
        locks.remove(lockFileName);
    }

    @Override
    public void publish(LogRecord lr) {
        super.publish(lr);
        flush();
    }

    private void open(File file, boolean append) throws FileNotFoundException {
        FileOutputStream fout = new FileOutputStream(file.toString(), append);
        BufferedOutputStream bout = new BufferedOutputStream(fout);
        setOutput(bout);
    }

    private File generate(String pattern, int generation, int unique) {
        int ix = 0;
        File file = null;
        String word = "";
        while (ix < pattern.length()) {
            char ch = pattern.charAt(ix);
            ix++;
            char ch2 = 0;
            if (ix < pattern.length()) {
                ch2 = Character.toLowerCase(pattern.charAt(ix));
            }
            if (ch == '/') {
                if (file == null) {
                    file = new File(word);
                }else {
                    file = new File(file, word);
                }
                word = "";
                continue;
            } else if (ch == '%') {
                if (ch2 == 't') {
                    String tempDir = System.getProperty("java.io.tmpdir");
                    if (tempDir == null) {
                        tempDir = System.getProperty("user.home");
                    }
                    file = new File(tempDir);
                    ix++;
                    word = "";
                    continue;
                } else if (ch2 == 'h') {
                    file = new File(System.getProperty("user.home"));
                    ix++;
                    word = "";
                    continue;
                } else if (ch2 == 'u') {
                    word = word + unique;
                    ix++;
                    continue;
                } else if (ch2 == '%') {
                    word = word + "%";
                    ix++;
                    continue;
                }
            }
            word = word + ch;
        }
        if (word.length() > 0) {
            if (file == null) {
                file = new File(word);
            } else {
                file = new File(file, word);
            }
        }
        return file;
    }

}